package com.ls.stack;

/**
 * @program: dataStructure
 * @author: lishun
 * @create: 2021-12-04 23:15
 **/

import lombok.Data;
/**
 * 链表实现栈
 */
@Data
public class LinkStack<T> {

    private Node<T> top;

    @Data
    class Node<T>{
        private T data;
        private Node next;

        public Node(T data) {
            this.data = data;
        }
    }

    //判断栈是否为空
    public boolean isEmpty(){
        Node cur = top;
        if (top==null){
            return true;
        }
        return false;
    }

    // 入栈操作
    public void push(T value){
        Node node = new Node(value);
        if (this.top==null){
            // 如果栈为空，则直接top指向新进的节点
            this.top = node;
            return;
        }
        // 插入链表头部
        node.next = this.top;

        this.top = node;
    }
    // 弹栈操作 -1表示栈空了
    public T    pop(){
        if (top == null){
            throw new RuntimeException("栈空了");
        }
        T result = (T) top.data;
        this.top = this.top.next;
        return result;
    }
    public void show(){
        if (top==null){
            throw new RuntimeException("栈空了");
        }
        Node cur = this.top;
        while (cur!=null){
            System.out.print(cur.data+"-->");
            cur = cur.getNext();
        }
        System.out.println();
    }

    public static void main(String[] args) {
        LinkStack<Integer> linkStack = new LinkStack();
        linkStack.push(1);
        linkStack.push(2);
        linkStack.push(3);
        linkStack.push(4);
        linkStack.push(5);
        while (true){
            System.out.println(linkStack.pop());
        }
//        linkStack.show();
    }



}
